﻿#pragma once
#pragma once

#include "util.h"
#include "..//ResourseManager//TextureAtlasAsset.h"

#include <functional>
#include <graphics.h>

//动画管理，用于处理帧动画
class Animation
{
public:
	Animation() = default;
	~Animation() = default;
	//利用atlas初始化
	Animation(std::shared_ptr<TextureAtlasAsset> atlas, int interval = 100, bool if_loop = true) :atlas(atlas), interval(interval), is_loop(if_loop)
	{
		is_atlas_loaded = true, self_manage_atlas = false;
	}

	//用户用路径直接初始化
	Animation(const std::string& id, LPCTSTR framePathFormat,
		int frameCount,
		int interval = 100,
		bool isLoop = false)
	{
		atlas = std::make_shared<TextureAtlasAsset>(id, framePathFormat, frameCount);
		atlas->Load();
		is_atlas_loaded = true;
		self_manage_atlas = true;
	}
	//卸载atlas中的资源,及atlas:当assetmanager没有调用的时候使用
	void UnloadAtlas()
	{
		if (is_atlas_loaded)
		{
			if (atlas) {
				atlas->Unload();
				atlas = nullptr;
			}
		}
	}
	void reset()
	{
		timer = 0;
		idx_frame = 0;
	}

	void set_atlas(std::shared_ptr<TextureAtlasAsset> new_TextureAtlasAsset)
	{
		reset();
		atlas = new_TextureAtlasAsset;
		is_atlas_loaded = true;
	}
	//set 参数: is_loop, interval, idx_frame, 动画callback，逐帧callback
	void set_loop(bool flag)
	{
		is_loop = flag;
	}

	void set_interval(int ms)
	{
		interval = ms;
	}

	void set_idx_frame(int frame) {
		idx_frame = frame;
	}

	void set_callback(std::function<void()> callback)
	{
		this->callback = callback;
	}

	void set_frame_callback(std::function<void(int)> callback) {
		this->frame_callback = callback;
	}
	void set_self_manage_atalas(bool if_self_manage)
	{
		self_manage_atlas = if_self_manage;
	}
	void set_is_atlas_loaded(bool is)
	{
		is_atlas_loaded = is;
	}
	//get 参数: idx_frame, frame
	int get_idx_frame()
	{
		return idx_frame;
	}

	IMAGE* get_frame()
	{
		return atlas->GetFrame(idx_frame);
	}

	std::shared_ptr<TextureAtlasAsset> GetAtlas()
	{
		return atlas;
	}

	int GetInterval()
	{
		return interval;
	}

	bool GetIsloop()
	{
		return is_loop;
	}

	int GetFrameCount()
	{
		return atlas->GetFrameCount();
	}
	std::function<void()> GetCallback()
	{
		return callback;
	}
	//check animation finished
	bool check_finished()
	{
		return (idx_frame == atlas->GetFrameCount() - 1);
	}


	//更新帧索引
	void on_update(int delta)
	{
		timer += delta;
		if (timer >= interval)
		{
			timer = 0;
			idx_frame++;
			if (frame_callback) frame_callback(idx_frame); // 触发回调
			if (idx_frame >= atlas->GetFrameCount())
			{
				idx_frame = is_loop ? 0 : atlas->GetFrameCount() - 1;
				if (!is_loop && callback)
					callback();
			}
		}
	}

	//绘制动画帧
	void on_draw(const Camera& camera, int x, int y) const
	{
		putimage_alpha(camera, x, y, atlas->GetFrame(idx_frame));
	}



private:
	bool is_atlas_loaded = false;
	bool self_manage_atlas = true;

	int timer = 0; //计时器
	int interval = 0; //播放速度
	int idx_frame = 0; //序列帧索引
	bool is_loop = true; //是否循环绘制
	std::shared_ptr<TextureAtlasAsset> atlas = nullptr;
	std::function<void()> callback;
	std::function<void(int)> frame_callback;
};
